// 导包
const fs = require('fs');
const path = require('path');
const sendEmail = require('./sendEmail');
// // 生成ID
// const { v4: uuidv4 } = require('uuid');
const qq = require('./qq');
// 导入已封装的数据函数
const db = require('../../config/db');
const PROJECT_NAME = qq.name;
const FROM_EMAIL = qq.email;//开发者邮箱

// 储存验证码的方案：
// 1: 写入.txt文件
// 2: 储存在数据库(推荐)
// 3: 使用nodejs储存机制
class Email {
    // 记录延迟函数的
    static delay = null;

    // captcha 验证码    captcha_time 接收到验证码时的时间

    // 发送邮件
    static async sendEmailVerification(email) {
        return new Promise((resolve, reject) => {
            // 查询数据库，判断是否已经发送过验证码
            let sql = `SELECT email FROM db_captcha WHERE email='${email}'`;
            db.query(sql)
                .then(async (rows) => {
                    if (rows.length >= 1) {
                        resolve({
                            code: 1,
                            msg: '已发送验证码，请勿重复发送。60秒后重新发送。'
                        });
                    } else {
                        // 生成验证码
                        let captcha = Math.random().toString().slice(-6); // 生成六位随机数
                        let captcha_time = new Date().getTime();

                        // 发送邮件内容
                        let emailContent = {
                            title: `${PROJECT_NAME}---邮箱验证码`,
                            body: `
                                <h1>您好：</h1>
                                <p style="font-size: 18px;color:#000;">
                                    您的验证码为：<span style="font-size: 16px;color:#f00;"><b>${captcha}</b>,</span>
                                    <p>您当前正在${PROJECT_NAME}账号，验证码告知他人将会导致数据信息被盗，请勿泄露!</p>
                                </p>
                                <p style="font-size: 1.5rem;color:#999;">60秒内有效</p>
                            `
                        };

                        // 发送邮件
                        await sendEmail.send({
                            from: FROM_EMAIL,
                            to: email,
                            subject: emailContent.title,
                            html: emailContent.body
                        });

                        // 将验证码存入数据库
                        Email.writeEmailCode(email, captcha, captcha_time)
                            .then(() => {
                                // 发送成功
                                resolve({
                                    code: 200,
                                    msg: '发送验证码成功。'
                                });

                                // 设置延迟，60秒后删除验证码
                                if (Email.delay != null) {
                                    clearTimeout(Email.delay);
                                }
                                Email.delay = setTimeout(() => {
                                    Email.removeEmailCode(email);
                                    Email.delay = null;
                                }, 60 * 1000);
                            })
                            .catch(() => {
                                // 存入数据库失败
                                reject({
                                    code: -1,
                                    msg: '发送邮箱验证发生异常。'
                                });
                            });
                    }
                })
                .catch(() => {
                    // 查询数据库异常
                    reject({
                        code: -1,
                        msg: '服务端发生异常。'
                    });
                });
        });
    }


    // 添加验证码
    static async writeEmailCode(email, captcha, captcha_time) {
        // console.log('x.0',{email,captcha,captcha_time})
        return new Promise((resolve, reject) => {
            // 执行插入数据的sql语句
            let sql = `insert into db_captcha(email,captcha,captcha_time) values('${email}','${captcha}','${captcha_time}')`;
            db.query(sql)
                .then(
                    rows => {
                        resolve({
                            code: 200,
                            msg: '添加验证码成功。'
                        })
                    }
                )
                .catch(
                    err => {
                        reject({
                            code: -1,
                            msg: '添加验证码失败。',
                            err
                        })
                    }
                )
        })
    }

    // 删除验证码
    static async removeEmailCode(email, captcha) {
        return new Promise((resolve, reject) => {
            // 执行删除数据的sql语句
            let sql = `delete from db_captcha where email = '${email}' and captcha = '${captcha}'`;
            db.query(sql)
                .then(
                    () => {
                        resolve({
                            code: 200,
                            msg: '删除验证码成功。'
                        })
                    }
                )
                .catch(
                    err => {
                        resolve({
                            code: -1,
                            msg: '删除验证码失败。',
                            err
                        })
                    }

                )
        })
    }

    // 判断邮箱的验证码是否是过期(是否有该验证码)
    static async verifyEmailCode(email, captcha) {
        // console.log('x.1',{email,captcha})
        // 判断邮箱和验证码是否匹配
        return new Promise((resolve, reject) => {
            // 执行查询数据的sql语句
            let sql = `select email from db_captcha where email = '${email}' and captcha='${captcha}'`;
            db.query(sql)
                .then(
                    rows => {
                        // console.log("x.3",rows)
                        // console.log("x.4",rows.length)
                        if (rows.length === 1) {
                            resolve({
                                code: 200,
                                msg: '邮箱验证成功。'
                            })

                        }
                        else {
                            // console.log('x.2',{email,captcha})
                            resolve({
                                code: -1,
                                msg: '邮箱验证失败1111。'
                            })
                        }
                    },

                    err => {
                        reject({
                            code: -1,
                            msg: '邮箱验证失败2222。',
                            err
                        })
                    }
                )
        })
    }

}
module.exports = Email;